<template>
  <div class="bg-white rounded-lg shadow-lg p-6">
    <div ref="chartRef" class="w-full h-[400px]"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  ToolboxComponent,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册 ECharts 组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  ToolboxComponent,
  BarChart,
  CanvasRenderer,
]);

const chartRef = ref(null);
let chartInstance = null;

// 图表配置
const chartOptions = {
  title: {
    text: '月度销售数据统计',
    left: 'center',
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  toolbox: {
    show: true,
    feature: {
      saveAsImage: {},
    },
  },
  xAxis: {
    type: 'category',
    data: ['一月', '二月', '三月', '四月', '五月', '六月'],
  },
  yAxis: {
    type: 'value',
    name: '销售额 (万元)',
  },
  series: [
    {
      name: '产品A',
      type: 'bar',
      data: [120, 132, 101, 134, 90, 230],
      itemStyle: {
        color: '#36CFC9',
      },
    },
    {
      name: '产品B',
      type: 'bar',
      data: [220, 182, 191, 234, 290, 330],
      itemStyle: {
        color: '#722ED1',
      },
    },
  ],
};

onMounted(() => {
  nextTick(() => {
    initChart();
    // 监听窗口大小变化，调整图表
    window.addEventListener('resize', handleResize);
  });
});

// 初始化图表
const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
    chartInstance.setOption(chartOptions);
  }
};

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 组件卸载时销毁图表实例
const onUnmounted = () => {
  if (chartInstance) {
    chartInstance.dispose();
    window.removeEventListener('resize', handleResize);
  }
};
</script>

<style scoped>
.bg-white {
  background-color: #ffffff;
}
.rounded-lg {
  border-radius: 0.5rem;
}
.shadow-lg {
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}
.p-6 {
  padding: 1.5rem;
}
.w-full {
  width: 100%;
}
.h-\[400px\] {
  height: 400px;
}
</style>  